#include "mqueue.h"

void mqueue_init(mqueue_t *queue, void *items, mqueue_queue_size_t size, mqueue_data_size_t data_size)
{
    queue->head = 0;
    queue->tail = 0;
    queue->count = 0;
    queue->size = size;
    queue->data_size = data_size;
    queue->data = items;
}

unsigned char mqueue_in(mqueue_t *queue, void *item)
{
    unsigned char *data = (unsigned char *)item;
    mqueue_queue_size_t i;

    if(mqueue_is_full(queue))
    {
        return 0;
    }

    for(i = 0; i < queue->data_size; i++)
    {
        queue->data[queue->tail * queue->data_size + i] = data[i];
    }

    queue->count++;
    queue->tail = (queue->tail + 1) % queue->size;

    return 1;
}

void *mqueue_first(mqueue_t *queue)
{
    if(mqueue_is_empty(queue))
    {
        return NULL;
    }

    return queue->data + (queue->head * queue->data_size);
}

void mqueue_out(mqueue_t *queue)
{
    if(!mqueue_is_empty(queue))
    {
        queue->count--;
        queue->head = (queue->head + 1) % queue->size;
    }
}

unsigned char mqueue_is_full(mqueue_t *queue)
{
    return queue->count == queue->size;
}

unsigned char mqueue_is_empty(mqueue_t *queue)
{
    return queue->count == 0;
}
